package cn.yikaojiuguo.student.ui.usercenter;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.yikaojiuguo.student.R;
import cn.yikaojiuguo.student.app.YiKaoApplication;
import cn.yikaojiuguo.student.support.simple.ArgsConstants;
import cn.yikaojiuguo.student.support.simple.SimpleTextWatcher;
import cn.yikaojiuguo.student.support.simple.UrlConstants;
import cn.yikaojiuguo.student.support.utils.LogUtil;
import cn.yikaojiuguo.student.support.utils.RequestUtil;
import cn.yikaojiuguo.student.support.utils.ToastUtil;
import cn.yikaojiuguo.student.support.utils.Util;
import cn.yikaojiuguo.student.support.volley.Response;
import cn.yikaojiuguo.student.ui.base.BaseLoginActivity;
import cn.yikaojiuguo.student.ui.global.SocialLoginPopupWindow;

public class CaptchaInputActivity extends BaseLoginActivity {

    @Bind(R.id.et1)
    EditText mEt1;
    @Bind(R.id.et2)
    EditText mEt2;
    @Bind(R.id.et3)
    EditText mEt3;
    @Bind(R.id.et4)
    EditText mEt4;
    @Bind(R.id.ll_code)
    LinearLayout mLl_code;
    @Bind(R.id.tv_tip)
    TextView mTv_tip;
    @Bind(R.id.rl_root)
    RelativeLayout mRl_root;
    private List<EditText> list;
    private int index = 1;
    private int count;
    private SpannableString ss;
    //计时器
    private TimeCount timeCount;
    //验证码
    private String mCode;
    //手机号
    private String mNumber;

    private SocialLoginPopupWindow mPopupWindow;

    public static Intent newIntent(String number,String code) {
        Intent intent = new Intent(YiKaoApplication.getInstance(),CaptchaInputActivity.class);
        intent.putExtra(ArgsConstants.NUMBER,number);
        intent.putExtra(ArgsConstants.CODE,code);
        return intent;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_captcha_input);
        ButterKnife.bind(this);
        initPopupWindow();
        mCode = getIntent().getStringExtra(ArgsConstants.CODE);
        mNumber = getIntent().getStringExtra(ArgsConstants.NUMBER);
        timeCount = new TimeCount(60000,1000);
        timeCount.start();
        ss = new SpannableString("还没收到短信验证码？赶紧\n点击这里从新发送");
        ss.setSpan(new UnderlineSpan(), 13, 17, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.text_blue_deep)), 13,
                17, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new Clickable(CaptchaInputActivity.this), 13, 17, Spanned
                .SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.text_blue_deep)), 13,
                17, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTv_tip.setText("请输入收到的短信验证码\n60秒后可从新发送");
        mTv_tip.setMovementMethod(LinkMovementMethod.getInstance());
        initEvents();
    }

    private void initPopupWindow() {
        mPopupWindow = new SocialLoginPopupWindow(this,0.95f,0.2f);
        mPopupWindow.setAnimationStyle(R.style.anim_popup_from_bottom);
    }

    private void initEvents() {
        list = new ArrayList<EditText>(4);
        list.add(mEt1);
        list.add(mEt2);
        list.add(mEt3);
        list.add(mEt4);
        mLl_code.setOnClickListener(this);
        mEt1.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 1) {
                    mEt1.clearFocus();
                    mEt2.requestFocus();
                }

            }
        });
        mEt2.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 1) {
                    mEt2.clearFocus();
                    mEt3.requestFocus();
                }

            }
        });
        mEt3.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 1) {
                    mEt3.clearFocus();
                    mEt4.requestFocus();
                    count = 1;
                }

            }
        });
        mEt4.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 1) {
                    count = 0;
                    if(checkCode()) {//验证码正确
                        startActivity(ChooseMajorActivity.newIntent());
                        finish();
                        rightEnter();
                    } else {//验证码不正确
                        // TODO 等待文案
                        ToastUtil.showToast(CaptchaInputActivity.this,"请输入正确的验证码！");
                    }
                }

            }
        });
        YiKaoApplication.putChooseMajorIndex(-1);
        YiKaoApplication.putChooseGradeIndex(-1);
        Util.openSoftInput(getWindow().getDecorView());
    }

    /**
     * 检查验证码是否正确
     */
    private boolean checkCode() {
        String code = "";
        for (EditText et:list) {
            code+=et.getText().toString().trim();
        }
        if(mCode.equals(code)) {
            return true;
        } else {
            return false;
        }

    }

    @Override
    protected String getOperationText() {
        return getResources().getString(R.string.activity_login_operation_text_more);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_code:
                Util.openSoftInput(getWindow().getDecorView());
                break;
            case R.id.tv_tip://重新发送验证码
                //showProgressDialog();
                String requestUrl = UrlConstants.SEND_CODE + "&mobile=" + mNumber + "&etype=" + 1;
                RequestUtil.requestGet(requestUrl, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        //dismissProgressDialog();
                        if(response!=null && response.optBoolean("success")) {
                            mCode = response.optString("message");
                            LogUtil.showInfoLog("resend code","resend code success");
                            timeCount.start();
                        }
                    }
                },null,mTag);
                break;
            case R.id.iv_back:
                startActivity(new Intent(CaptchaInputActivity.this,LoginActivity.class));
                finish();
                leftEnter();
                break;
            case R.id.tv_operation:
                Util.closeSoftInput(this);
                mPopupWindow.showAtLocation(mRl_root, Gravity.BOTTOM, 0, 0);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DEL) {
            String str = "";
            for (EditText et : list) {
                str += et.getText().toString().trim();
            }
            index = str.length() + 1;
            if (index == 4) {
                count++;
                if (count == 2) {
                    list.get(3).clearFocus();
                    list.get(2).requestFocus();
                    list.get(2).setText("");
                }
            } else {
                count = 0;
                if (index > 1) {
                    list.get(index - 1).clearFocus();
                    list.get(index - 2).requestFocus();
                    list.get(index - 2).setText("");
                    index--;
                } else if (index == 1) {
                    list.get(index - 1).requestFocus();
                    list.get(index - 1).setText("");
                }

            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timeCount!=null) {
            timeCount.cancel();
        }
    }

    class Clickable extends ClickableSpan{
        private final View.OnClickListener mListener;

        public Clickable(View.OnClickListener listener) {
            mListener = listener;
        }

        @Override
        public void onClick(View view) {
            mListener.onClick(view);
        }

    }

    class TimeCount extends CountDownTimer {

        /**
         * @param millisInFuture 总时长
         * @param countDownInterval 时间间隔
         */
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mTv_tip.setText("请输入收到的短信验证码\n" + (int)millisUntilFinished/1000 + "秒后可从新发送");
        }

        @Override
        public void onFinish() {
            mTv_tip.setText(ss);
        }
    }

    @Override
    public void onBackPressed() {
        mIv_back.performClick();
    }
}
